#!/usr/bin/env python
import socket, re
from threading import Thread
class ResolveIP(Thread):
  def __init__(self, ip):
    Thread.__init__(self)
    self.ip = ip
    self.re_ip = re.compile(r'^\d+\.\d+\.\d+\.\d+$')
    self.host = 'Unknown'
    self.completehost = ''
    self.aliaslist = []
    self.ipaddrlist = []
    self.resolved = 0
    self.unresolved = {}
  def run(self):
    a = ()
    if self.re_ip.search(self.ip):
      self.resolve(self.ip)
    else:
      ips = self.ip.split('/')
      #print ips
      for ip in ips:
        if self.re_ip.search(ip):
          self.resolve(ip)
    
  def resolve(self, ip):
    try :
      a = socket.gethostbyaddr(ip)
      #print a
      l = []
      self.completehost = a[0]
      l = a[0].split('.')
      #print "%s.%s" % (list[-2], list[-1])
      self.host = "%s.%s" % (l[-2], l[-1])
      if len(self.host) <= 6:
        self.host = str(l[-3])+"."+self.host
      
      #print self.host
      self.aliaslist = a[1]
      self.ipaddrlist = a[2]
      self.resolved += 1
    except Exception, (errno):
      #print errno[1]
      self.unresolved.setdefault(errno[0], 0)
      self.unresolved[errno[0]] += 1
    
  def __str__(self):
    if self.host != '' or self.aliaslist != [] or self.ipaddrlist != []:
      response = """
      Host : %s
      """ % self.host
      response += """Alias list :
      """
      for alias in self.aliaslist:
        response += "\t\t\t"+alias+"\n"
      
      response += """IP Address list :
      """
      for ip in self.ipaddrlist:
        response += "\t\t\t"+ip+"\n"
      return response

